package cn.echo.consul.manager.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * JSON转换类
 *
 * @author lonyee
 */
public class JsonUtil {
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private volatile static ObjectMapper mapper;
    private final static String DATE_TIME_FORMATTER = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 获取ObjectMapper实例
     *
     * @return
     */
    public static ObjectMapper getInstance() {
        if (mapper == null) {
            synchronized (ObjectMapper.class) {
                if (mapper == null) {
                    mapper = getNewInstance();
                }
            }
        }
        return mapper;
    }

    /**
     * 获取新的ObjectMapper实例
     *
     * @return
     */
    public static ObjectMapper getNewInstance() {
        //转换器
        final PolymorphicTypeValidator validator = BasicPolymorphicTypeValidator.builder()
                .allowIfBaseType(Object.class).build();
        ObjectMapper objectMapper = new ObjectMapper();

        //修复Long类型太长，丢失精度问题
        //SimpleModule simpleModule = new SimpleModule();
        //simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        //simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        //simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
        //simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
        //objectMapper.registerModule(simpleModule);
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); //忽略映射属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMATTER));
        return objectMapper;
    }

    /**
     * 对象转JSON字符串
     */
    public static String toJson(Object object) {
        try {
            ObjectMapper objectMapper = JsonUtil.getInstance();
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            logger.warn("toJson write json value error", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * JSON字符串转java对象
     */
    public static <T> T fromJson(String json, Class<T> valueType) {
        try {
            if (StringUtils.isEmpty(json)) {
                return null;
            }
            ObjectMapper objectMapper = JsonUtil.getInstance();
            return objectMapper.readValue(json, valueType);
        } catch (Exception e) {
            logger.warn("fromJson class read json value error", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * JSON字符串转java对象 (Model中含有List<T>)
     * 针对错误：java.util.LinkedHashMap cannot be cast to ...
     */
    public static <T> T fromJson(String json, TypeReference<T> valueTypeRef) {
        try {
            if (ObjectUtils.isEmpty(json)) {
                return null;
            }
            ObjectMapper objectMapper = JsonUtil.getInstance();
            return objectMapper.readValue(json, valueTypeRef);
        } catch (Exception e) {
            logger.warn("fromJson typeReference read json value error", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * JSON字符串转java对象
     */
    public static <T> T fromJson(Reader reader, Class<T> valueType) {
        try {
            if (ObjectUtils.isEmpty(reader)) {
                return null;
            }
            ObjectMapper objectMapper = JsonUtil.getInstance();
            return objectMapper.readValue(reader, valueType);
        } catch (Exception e) {
            logger.warn("fromJson reader read json value error", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * JSON字符串转list列表
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> toList(String json, Class<T> valueType) {
        try {
            if (ObjectUtils.isEmpty(json)) {
                return new ArrayList<>();
            }
            ObjectMapper objectMapper = JsonUtil.getInstance();
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, valueType);
            return (List<T>) objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            logger.warn("toList class read json value error", e);
            return new ArrayList<>();
        }
    }

    /**
     * JSON字符串转list列表
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> toList(String json, TypeReference<List<T>> valueTypeRef) {
        try {
            if (ObjectUtils.isEmpty(json)) {
                return new ArrayList<>();
            }
            ObjectMapper objectMapper = JsonUtil.getInstance();
            return objectMapper.readValue(json, valueTypeRef);
        } catch (Exception e) {
            logger.warn("toList typeReference read json value error", e);
            return new ArrayList<>();
        }
    }

    /**
     * map convert to javaBean
     */
    public static <T> T mapToBean(Map map, Class<T> clazz) {
        ObjectMapper objectMapper = JsonUtil.getInstance();
        return objectMapper.convertValue(map, clazz);
    }

    /**
     * map convert to javaBean
     */
    public static <T> T mapToBean(Map map, TypeReference<T> valueTypeRef) {
        ObjectMapper objectMapper = JsonUtil.getInstance();
        return objectMapper.convertValue(map, valueTypeRef);
    }
}
